package com.ttx.zookeeper.lock.curator;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessLock;
import org.apache.curator.framework.recipes.locks.InterProcessReadWriteLock;
import org.apache.curator.retry.ExponentialBackoffRetry;

import java.util.concurrent.TimeUnit;

/**
 * 共享锁(读写锁)
 * @author TimFruit
 * @date 20-2-28 上午9:42
 */
public class CuratorSLockReadLockSample {
    public static void main(String[] args) throws Exception {
        String connectString="127.0.0.1:2181," +
                "127.0.0.1:2182," +
                "127.0.0.1:2183";

        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
        CuratorFramework client = CuratorFrameworkFactory.newClient(connectString, retryPolicy);
        client.start();

        String lockPath="/slock-curator";

        InterProcessReadWriteLock readWritelock=new InterProcessReadWriteLock(client, lockPath);

        InterProcessLock lock=readWritelock.readLock();
        System.out.println("准备获取读锁...");
        lock.acquire();
        System.out.println("获取成功...");



        System.out.println("休眠等待30s...");
        TimeUnit.SECONDS.sleep(30);

        System.out.println("释放锁...");
        lock.release();
    }
}
